<?php
namespace App\Http\Controllers\Business\App\Wallet;

use App\Http\Controllers\Business\App\Auth\AppAuth;
use App\Models\AllInPay;
use App\Models\Comment;
use App\Models\OrderRefund;
use App\Models\User;
use App\Models\Recharge;
use App\Models\RedEnvelope;
use App\Models\Order;
use App\Models\Shop;
use App\Models\City;
use App\Models\DoubleCoupon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Log;

class  Wallet
{
    //钱包首页
    public static function index($userid){
        if(!$userid) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $data = User::where('id',$userid)->select('mobile','doublecoupons','balance','avatar','nickname','savemoney','created_at','firstrechargetime','firstordertime','firstshopname')->first();
        $data['rechargecount'] = Recharge::where('userid', $userid)->get()->count();
        $data['doublemoney'] = Recharge::where(array('userid'=>$userid,'status'=>'1','doublestatus'=>'0'))->sum('doublemoney');
        if($data['doublemoney'] == '') {
            $data['doublemoney'] = '0.0';
        }
        $doubleCouponCount = DoubleCoupon::where(array('userid' => $userid, 'type'=>'recharge'))->where('endtime', '>', date('Y-m-d H:i:s', time()))->get()->count();
        if($doubleCouponCount>0) {
            $data['isdoublecoupon'] = '1';
        } else {
            $data['isdoublecoupon'] = '0';
        }
        $data['sumrechargemoney'] = Recharge::where(array('userid'=>$userid,'status'=>'1'))->sum('money');
        $data['sumordermoney'] = Order::where('userid',$userid)->where('refundstatus', 0)->sum('actualamount');
        $data['sumday'] = self::diffBetweenTwoDays($data['created_at'], date('Y-m-d H:i:s',time()));
        $data['waitcommentorder'] = Order::where('userid', $userid)->where('commentstatus', '0')->get()->count();
        return ['status'=>'success','data'=>$data];
    }
    //订单列表
    public static function payOrderList($userId, $commentStatus='') {
        if(!$userId) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        if($commentStatus == '1') {
            $data = Order::where('userid', $userId)->where('commentstatus', $commentStatus)
                ->select('ordernumber', 'shopname', 'orderamount', 'actualamount', 'commentstatus', 'refundstatus', 'created_at')
                ->orderBy('created_at', 'desc')->paginate(20);
        } elseif($commentStatus == '0') {
            $data = Order::where('userid', $userId)->where('commentstatus', $commentStatus)->where('refundstatus', 0)
                ->select('ordernumber', 'shopname', 'orderamount', 'actualamount', 'commentstatus', 'refundstatus', 'created_at')
                ->orderBy('created_at', 'desc')->paginate(20);
        } else {
            $data = Order::where('userid', $userId)
                ->select('ordernumber', 'shopname', 'orderamount', 'actualamount', 'commentstatus', 'refundstatus', 'created_at')
                ->orderBy('created_at', 'desc')->paginate(20);
        }
        return ['status'=>'success','data'=>$data];
    }
    //充值列表
    public static function rechargeOrderList($userid) {
        if(!$userid) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $data = Recharge::where(array('userid'=>$userid,'status'=>'1'))->select('rechargenumber','money','doublemoney','doublestatus','doubletime','created_at')
            ->orderBy('created_at','desc')->paginate(20);
        return ['status'=>'success','data'=>$data];
    }
    //翻贝轨迹
    public static function course($userid) {
        if(!$userid) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $data = User::where('id',$userid)->select('avatar','nickname','savemoney','created_at','firstrechargetime','firstordertime','firstshopname')->first();
        $data['sumrechargemoney'] = Recharge::where(array('userid'=>$userid,'status'=>'1'))->sum('money');
        $data['sumordermoney'] = Order::where('userid',$userid)->where('refundstatus', 0)->sum('actualamount');
        $data['sumday'] = self::diffBetweenTwoDays($data['created_at'], date('Y-m-d H:i:s',time()));
        return ['status'=>'success','data'=>$data];
    }
    //获取翻贝券，type 为 recharge, recommend
    public static function getDoubleCouponCountByType($userId, $type) {
        if(!$userId) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $count = DoubleCoupon::where('userid', $userId)->where('type', $type)->get()->count();
        if($count >0) {
            return ['status'=>'success', 'message'=>'有翻倍券'];
        } else {
            return ['status'=>'failed', 'message'=>'无翻倍券'];
        }
    }
    //通过userid 获取手机号
    public static function getMobileByUserId($userid) {
        if(!$userid) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $data = User::where('id', $userid)->pluck('mobile')->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //通过userid 获取用户余额
    public static function getBalanceByUserId($userId) {
        if(!$userId) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $data = User::where('id', $userId)->pluck('balance')->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //通过用户id获取最大红包金额
    public static function getRedEnvelopeMaxAmount($userId, $money) {
        if(!$userId||!$money) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        //TODO 红包条件还需要讨论
        $amount = RedEnvelope::where('userid', $userId)->where('status', 0)->where('amount', '<=', $money)
            ->where('endtime', '>=', date('Y-m-d'))
            ->orderBy('amount', 'desc')->orderBy('created_at', 'asc')->pluck('amount')->first();
        if($amount == '') {
            $amount = 0.00;
        }
        return ['status'=>'success', 'data'=>$amount];
    }
    //版本号v15 通过用户id获取最大红包金额
    public static function getRedEnvelopeMaxAmountByV15Version($userId, $money, $shopId) {
        if (!$userId || !$money || !$shopId) {
            return ['status' => 'failed', 'message' => '参数错误'];
        }
        $shop = Shop::where('id', $shopId)->where('status', 1)->first();
        if(!$shop) {
            return ['status' => 'failed', 'message' => '获取信息失败'];
        }
        //TODO 红包条件还需要讨论
        $GLOBALS['cityid'] = $shop->cityid;
        $amount = RedEnvelope::where('userid', $userId)->where(function($query) {
                $query->orwhere('cityid', $GLOBALS['cityid'])->orwhere('cityid', 0);
            })
            ->where('status', 0)->where('amount', '<=', $money)
            ->where('endtime', '>=', date('Y-m-d'))
            ->orderBy('amount', 'desc')->orderBy('created_at', 'asc')->pluck('amount')->first();
        if ($amount == '') {
            $amount = 0.00;
        }
        return ['status' => 'success', 'data' => $amount];
    }
    //新用户领取翻贝券
    public static function newUserDoubleCoupon($mobile){
        if(!$mobile) {
            return ['status'=>'failed','message'=>'无用户参数！'];
        }
        $userId = User::where('mobile', $mobile)->pluck('id')->first();
        if(!$userId) {
            return ['status'=>'failed', 'message'=>'参数错误！'];
        }
        $count = DoubleCoupon::where('userid', $userId)->where('type', 'recharge')->get()->count();
        if($count > 0) {
            return ['status'=>'failed', 'message'=>'已领取过，不能再领取了'];
        }
        $doublecoupon = new DoubleCoupon;
        $doublecoupon->userid = $userId;
        $doublecoupon->starttime = date('Y-m-d H:i:s',time());
        $time=time()+30*24*3600;
        $endtime=date('Y-m-d',$time);
        $doublecoupon->endtime = $endtime;
        $doublecoupon->status = '0';
        $doublecoupon->type = 'recharge';
        $doublecoupon->save();
        $user = User::find($userId)->increment('doublecoupons', 1);
        return ['status'=>'success','message'=>'领取成功！'];

    }
    //充值分享更新
    public static function updateDoubleTimeAfterShare($userId, $orderNumber) {
//        if(!$userId || !$orderNumber) {
//            return ['status'=>'failed', 'message'=>'参数不对'];
//        }
//        $recharge = Recharge::where('userid', $userId)->where('rechargenumber', $orderNumber)->first();
//        if(!$recharge) {
//            return ['status'=>'failed', 'message'=>'修改错误'];
//        }
//        $shareStatus = $recharge->sharestatus;
//        if($shareStatus != 1) {
//            $doubleTime = strtotime($recharge->doubletime) - 6 * 60 * 60;
//            $recharge->doubletime = date('Y-m-d H:i:s', $doubleTime);
//            $recharge->sharestatus = 1;
//            $recharge->save();
//        }
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //充值详情
    public static function rechargeDetails($userid,$rechargenumber) {
        if(!$userid || !$rechargenumber) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data = Recharge::where(array('userid'=>$userid,'rechargenumber'=>$rechargenumber))
            ->select('rechargenumber','money','fee', 'actualmoney','doublemoney','path','status','doublestatus','doubletime','sharestatus','created_at')->first();
        if(!$data) {
            $data = [
                'rechargenumber'=>$rechargenumber,
                'money' => '',
                'fee' => '',
                'actualmoney' => '',
                'doublemoney' => '',
                'path' => '',
                'status' => 0,
                'doublestatus' => 0,
                'doubletime' => '',
                'sharestatus' => 0,
                'created_at' => ''
            ];
            return ['status'=>'success','data'=>$data];
        }
        return ['status'=>'success','data'=>$data];
    }
    //订单详情
    public static function orderDetails($userid,$ordernumber) {
        if(!$userid || !$ordernumber) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data = Order::where('userid',$userid)->where('ordernumber', $ordernumber)
            ->select('ordernumber','shopid','shopname','orderamount','actualamount','redenvelopeamount','fee','commentstatus','bonus','bonusid','refundstatus','created_at')->first();
        if($data['commentstatus']=='1') {
            $data['comment'] = Comment::where('ordernumber',$data['ordernumber'])->select('score','content','picture','replycontent')->first();
        }
        if(($data['bonusid'] != '') && ($data['bonusid'] != 0) ) {
            $data['bonusinfo'] = RedEnvelope::where('red_envelopes.id', $data['bonusid'])
                ->join('city', 'red_envelopes.cityid', '=', 'city.id')
                ->select('red_envelopes.amount', 'red_envelopes.minimumamount', 'city.name as cityname', 'red_envelopes.endtime')
                ->first();
        } else {
            $data['bonusinfo'] = [
                'amount' => 0,
                'minimumamount' => 0,
                'cityname' => '',
                'endtime' => '0000-00-00 00:00:00'
            ];
        }
        if($data['refundstatus']) {
            $data['refundinfo'] = OrderRefund::where('ordernumber', $data['ordernumber'])->select('money as refundmoney', 'redenvelopeinfo', 'created_at as refundtime')->first();
        } else {
            $data['refundinfo'] = [
                'refundmoney' => 0,
                'redenvelopeinfo' => '',
                'refundtime' => '0000-00-00 00:00:00'
            ];
        }
        $data['shop'] = Shop::where('id', $data['shopid'])->select('logo','address', 'contactnumber')->first();
        return ['status'=>'success','data'=>$data];
    }
    //两天之间的相隔天数
    public static function diffBetweenTwoDays ($day1, $day2) {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return round(($second1 - $second2) / 86400);
    }
    //获取支付码， web端
    public static function getPayCode($userid) {
        if(!$userid) {
            //参数不对
            return ['status'=>'failed','message'=>'invalid_parameter'];
        }
        $paycode = Redis::get('PayCode:Userid:' . $userid);
        if($paycode) {
            if (strlen(Redis::get('PayCode:' . $paycode)) == 20) {
                $ordernumber = Redis::get('PayCode:' . $paycode);
                Redis::del('PayCode:' . $paycode);
                Redis::del('PayCode:Userid:' . $userid);
                //$ordernumber="123456789";
                return ['status' => 'success', 'message' => '付款成功！', 'data' => array('ordernumber' => $ordernumber)];
            }
            if (Redis::get('PayCode:' . $paycode) == 'balance is not enough') {
                //余额不足
                Redis::del('PayCode:' . $paycode);
                Redis::del('PayCode:Userid:' . $userid);
                return ['status' => 'failed', 'message' => 'balance_not_enough'];
            }
            if (Redis::get('PayCode:' . $paycode) == 'buynumberlimit') {
                //买单次数限制
                Redis::del('PayCode:' . $paycode);
                Redis::del('PayCode:Userid:' . $userid);
                return ['status' => 'failed', 'message' => '买单次数限制'];
            }
        }
        if ($paycode) {
            return ['status' => 'success', 'data' => array('paycode' => $paycode)];
        }
        $paycode = AppAuth::getRandChar(20);
        if (Redis::get('PayCode:' . $paycode)) {
            $paycode = AppAuth::getRandChar(20);
        }
        Redis::setex('PayCode:' . $paycode, 65, $userid);
        Redis::setex('PayCode:Userid:'.$userid, 65, $paycode);
        return ['status' => 'success', 'data' => array('paycode' => $paycode)];
    }
    //通过用户id获取支付码，app端
    public static function getPayCodeByUserId($userid) {
        if(!$userid) {
            return ['status'=>'failed','message'=>'invalid_parameter'];
        }
        $paycode = Redis::get('PayCode:Userid:' . $userid);
        if($paycode) {
            Redis::del('PayCode:' . $paycode);
            Redis::del('PayCode:Userid:' . $userid);
        }
        $paycode = AppAuth::getRandChar(20);
        if (Redis::get('PayCode:' . $paycode)) {
            $paycode = AppAuth::getRandChar(20);
        }
        Redis::setex('PayCode:' . $paycode, 65, $userid);
        Redis::setex('PayCode:Userid:' . $userid, 65, $paycode);
        return ['status' => 'success', 'data' => array('paycode' => $paycode)];
    }
    //获取支付状态
    public static function getPayStatus($userid) {
        if(!$userid) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $paycode = Redis::get('PayCode:Userid:' . $userid);
        if (strlen(Redis::get('PayCode:' . $paycode)) == 20) {
            $ordernumber = Redis::get('PayCode:' . $paycode);
            Redis::del('PayCode:' . $paycode);
            Redis::del('PayCode:Userid:' . $userid);
            $data = ['status'=>'2', 'ordernumber'=>$ordernumber];
            return ['status' => 'success', 'data' => $data];
        }
        if (Redis::get('PayCode:' . $paycode) == 'buynumberlimit') {
            //买单次数限制
            Redis::del('PayCode:' . $paycode);
            Redis::del('PayCode:Userid:' . $userid);
            $data = ['status'=>'3', 'ordernumber'=>''];
            return ['status' => 'success', 'data' => $data];
        }
        if (Redis::get('PayCode:' . $paycode) == 'balance is not enough') {
            //余额不足
            Redis::del('PayCode:' . $paycode);
            Redis::del('PayCode:Userid:' . $userid);
            $data = ['status'=>'1', 'ordernumber'=>''];
            return ['status' => 'success', 'data' => $data];
        }
        $data = ['status'=>'0', 'ordernumber'=>''];
        return ['status'=>'success', 'data'=>$data];
    }
    //web端充值准备
    public static function webReadyRecharge($userid,$money,$paytype,$openid='', $isdoublecoupon='0') {
        if(!$userid || !$money || !$paytype || ($paytype!='1' && $paytype != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data['userid'] = $userid;
        $data['money'] = $money;
        $mobile = User::where('id',$userid)->pluck('mobile')->first();
        $data['isdouble'] = User::where('id',$userid)->pluck('isdouble')->first();
        $data['isdoublecoupon'] = $isdoublecoupon;
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $ordernumber=$paytype.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$ordernumber,1200,json_encode($data));
            unset($data);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        if($paytype == '1') {
            //支付宝
            $alipay_config = new \Alipay_config();
            $alipay_config = $alipay_config->alipay_config();
            $payment_type = "1";
            $notify_url = env('WEB_URL')."fbwnotify/alinotify";
            $return_url = env('WEB_URL')."mobile/wallet/recharge/end?ordernumber=".$ordernumber;
            $out_trade_no = $ordernumber;
            $subject = '翻贝网-'.$ordernumber;
            $total_fee = $money;
            $show_url = env('WEB_URL');
            $body = $userid;
            $it_b_pay = '';
            $extern_token = '';
            $parameter = array(
                "service" => "alipay.wap.create.direct.pay.by.user",
                "partner" => trim($alipay_config['partner']),
                "seller_id" => trim($alipay_config['seller_id']),
                "payment_type"	=> $payment_type,
                "notify_url"	=> $notify_url,
                "return_url"	=> $return_url,
                "out_trade_no"	=> $out_trade_no,
                "subject"	=> $subject,
                "total_fee"	=> $total_fee,
                "show_url"	=> $show_url,
                "body"	=> $body,
                "it_b_pay"	=> $it_b_pay,
                "extern_token"	=> $extern_token,
                "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            );
            //建立请求
            $alipaySubmit = new \AlipaySubmit($alipay_config);
            $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
            return ['status'=>'success','data'=>$html_text];
        } elseif($paytype == '2') {
            //微信
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody('翻贝网-'.$ordernumber);
            $input->SetAttach($userid);
            $input->SetOut_trade_no($ordernumber);
            $input->SetTotal_fee($money*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 900));
            $input->SetGoods_tag("FBW");
            $input->SetNotify_url(env('WEB_URL')."fbwnotify/wechatnotify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid(Auth::user()->wxopenid);
            $orders = \WxPayApi::unifiedOrder($input,'2');
            $data['jsApiParameters'] = $tools->GetJsApiParameters($orders);
            $data['ordernumber'] = $ordernumber;
            if(!$data['jsApiParameters'])
            {
                return ['status'=>'failed','message'=>'统一下单失败！'];
            }
            return ['status'=>'success','data'=>$data];
        }
    }
    //web端充值准备，v2 2017-03-01
    public static function webReadyRechargeByV2Version($userid,$money,$paytype,$openid='', $isdoublecoupon='0') {
        if(!$userid || !$money || !$paytype || ($paytype!='1' && $paytype != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $isDouble = User::where('id',$userid)->pluck('isdouble')->first();
        if($isDouble) {
            $fee = 0.00;
            $actualmoney = $money;
        } else {
            $fee = env('RECHARGE_FEE') * $money;
            $actualmoney = (1+env('RECHARGE_FEE')) * $money;
        }
        $data['userid'] = $userid;
        $data['money'] = $money;
        $data['fee'] = $fee;
        $data['actualmoney'] = $actualmoney;
        $data['apiversion'] = 'v2';
        $mobile = User::where('id',$userid)->pluck('mobile')->first();
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $ordernumber=$paytype.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$ordernumber,1200,json_encode($data));
            unset($data);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        if($paytype == '1') {
            //支付宝
            $alipay_config = new \Alipay_config();
            $alipay_config = $alipay_config->alipay_config();
            $payment_type = "1";
            $notify_url = env('WEB_URL')."fbwnotify/alinotify";
            $return_url = env('WEB_URL')."mobile/wallet/recharge/end?ordernumber=".$ordernumber;
            $out_trade_no = $ordernumber;
            $subject = '翻贝网-'.$ordernumber;
            $total_fee = $actualmoney;
            $show_url = env('WEB_URL');
            $body = $userid;
            $it_b_pay = '';
            $extern_token = '';
            $parameter = array(
                "service" => "alipay.wap.create.direct.pay.by.user",
                "partner" => trim($alipay_config['partner']),
                "seller_id" => trim($alipay_config['seller_id']),
                "payment_type"	=> $payment_type,
                "notify_url"	=> $notify_url,
                "return_url"	=> $return_url,
                "out_trade_no"	=> $out_trade_no,
                "subject"	=> $subject,
                "total_fee"	=> $total_fee,
                "show_url"	=> $show_url,
                "body"	=> $body,
                "it_b_pay"	=> $it_b_pay,
                "extern_token"	=> $extern_token,
                "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            );
            //建立请求
            $alipaySubmit = new \AlipaySubmit($alipay_config);
            $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
            return ['status'=>'success','data'=>$html_text];
        } elseif($paytype == '2') {
            //微信
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody('翻贝网-'.$ordernumber);
            $input->SetAttach($userid);
            $input->SetOut_trade_no($ordernumber);
            $input->SetTotal_fee($actualmoney*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 900));
            $input->SetGoods_tag("FBW");
            $input->SetNotify_url(env('WEB_URL')."fbwnotify/wechatnotify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid(Auth::user()->wxopenid);
            $orders = \WxPayApi::unifiedOrder($input,'2');
            $data['jsApiParameters'] = $tools->GetJsApiParameters($orders);
            $data['ordernumber'] = $ordernumber;
            if(!$data['jsApiParameters']) {
                return ['status'=>'failed','message'=>'统一下单失败！'];
            }
            return ['status'=>'success','data'=>$data];
        }
    }
    //app充值准备
    public static function apiReadyRecharge($userid,$money,$paytype, $isdoublecoupon='0') {
        if(!$userid || !$money || !$paytype || ($paytype!='1' && $paytype != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data['userid'] = $userid;
        $data['money'] = $money;
        $data['isdouble'] = User::where('id',$userid)->pluck('isdouble')->first();
        $data['isdoublecoupon'] = $isdoublecoupon;
        $mobile = User::where('id',$userid)->pluck('mobile')->first();
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $ordernumber=$paytype.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$ordernumber,1200,json_encode($data));
            unset($data['userid']);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        if($paytype == '1') {
            //支付宝
            $alipay_config = new \Alipay_config();
            $alipay_config = $alipay_config->alipay_config();
            $alipay['app_id'] = $alipay_config['app_id'];
            $biz_content['timeout_express'] = '15m';
            $biz_content['seller_id'] = $alipay_config['seller_id'];
            $biz_content['product_code'] = 'QUICK_MSECURITY_PAY';
            $biz_content['total_amount'] = $money;
            $biz_content['subject'] = '翻贝网-'.$ordernumber;
            $biz_content['body'] = $userid;
            $biz_content['out_trade_no'] = $ordernumber;
            $alipay['biz_content'] = json_encode($biz_content);
            $alipay['charset'] = 'utf-8';
            $alipay['format'] = 'json';
            $alipay['method'] = 'alipay.trade.app.pay';
            $alipay['notify_url'] = env('WEB_URL')."fbwnotify/alinotify";
            $alipay['sign_type'] = 'RSA';
            $alipay['timestamp'] = date('Y-m-d H:i:s',time());
            $alipay['version'] = '1.0';
            $alipay['sign'] = self::rsaSign(self::createLinkstring($alipay),$alipay_config['private_key']);
            $data = [
                'data' => self::createLinkstringUrlencode($alipay),
                'ordernumber' => $ordernumber
            ];
            return ['status'=>'success','data'=>$data];
        } elseif ($paytype == '2') {
            //微信
            $input = new \WxPayUnifiedOrder();
            $input->SetBody('翻贝网-'.$ordernumber);
            $input->SetAttach($userid);
            $input->SetOut_trade_no(date($ordernumber));
            $input->SetTotal_fee($money*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 900));
            $input->SetGoods_tag("FBW");
            $input->SetNotify_url(env('WEB_URL')."fbwnotify/wechatnotify");
            $input->SetTrade_type("APP");
            $orders = \WxPayApi::unifiedOrder($input,'1');
            if(!$orders) {
                return ['status'=>'failed','message'=>'统一下单失败！'];
            }
            $retcode['appid']=$orders['appid'];
            $retcode['partnerid']=$orders['mch_id'];
            $retcode['prepayid']=$orders['prepay_id'];
            $retcode['noncestr']=$orders['nonce_str'];
            $retcode['package']='Sign=WXPay';
            $retcode['timestamp']=time();
            $retcode['sign']=self::MakeSign($retcode);
            $data = [
                'data' => $retcode,
                'ordernumber' => $ordernumber
            ];
            return ['status'=>'success','data'=>$data];
        }
    }
    //v2版本的app充值准备 2017-02-17,
    public static function apiReadyRechargeByV2Version($userId,$money,$payType) {
        if(!$userId || !$money || !$payType || ($payType!='1' && $payType != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $actualMoney = (1 + env('RECHARGE_FEE')) * $money;
        $fee = $money * env('RECHARGE_FEE');
        if(User::where('id', $userId)->pluck('isdouble')->first() == 1) {
            //内部用户免手续费
            $actualMoney = $money;
            $fee = 0.00;
        }
        $actualMoney = $actualMoney;
        $data['userid'] = $userId;
        $data['money'] = $money;
        $data['actualmoney'] = $actualMoney;
        $data['fee'] = $fee;
        $data['apiversion'] = 'v2';
        $mobile = User::where('id',$userId)->pluck('mobile')->first();
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $orderNumber=$payType.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$orderNumber,1200,json_encode($data));
            unset($data['userid']);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        if($payType == '1') {
            //支付宝
            $alipay_config = new \Alipay_config();
            $alipay_config = $alipay_config->alipay_config();
            $alipay['app_id'] = $alipay_config['app_id'];
            $biz_content['timeout_express'] = '15m';
            $biz_content['seller_id'] = $alipay_config['seller_id'];
            $biz_content['product_code'] = 'QUICK_MSECURITY_PAY';
            $biz_content['total_amount'] = $actualMoney;
            $biz_content['subject'] = '翻贝网-'.$orderNumber;
            $biz_content['body'] = $userId;
            $biz_content['out_trade_no'] = $orderNumber;
            $alipay['biz_content'] = json_encode($biz_content);
            $alipay['charset'] = 'utf-8';
            $alipay['format'] = 'json';
            $alipay['method'] = 'alipay.trade.app.pay';
            $alipay['notify_url'] = env('WEB_URL')."fbwnotify/alinotify";
            $alipay['sign_type'] = 'RSA';
            $alipay['timestamp'] = date('Y-m-d H:i:s',time());
            $alipay['version'] = '1.0';
            $alipay['sign'] = self::rsaSign(self::createLinkstring($alipay),$alipay_config['private_key']);
            $data = [
                'data' => self::createLinkstringUrlencode($alipay),
                'ordernumber' => $orderNumber
            ];
            return ['status'=>'success','data'=>$data];
        } elseif ($payType == '2') {
            //微信
            $input = new \WxPayUnifiedOrder();
            $input->SetBody('翻贝网-'.$orderNumber);
            $input->SetAttach($userId);
            $input->SetOut_trade_no(date($orderNumber));
            $input->SetTotal_fee($actualMoney*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 900));
            $input->SetGoods_tag("FBW");
            $input->SetNotify_url(env('WEB_URL')."fbwnotify/wechatnotify");
            $input->SetTrade_type("APP");
            $orders = \WxPayApi::unifiedOrder($input,'1');
            if(!$orders) {
                return ['status'=>'failed','message'=>'统一下单失败！'];
            }
            $retcode['appid']=$orders['appid'];
            $retcode['partnerid']=$orders['mch_id'];
            $retcode['prepayid']=$orders['prepay_id'];
            $retcode['noncestr']=$orders['nonce_str'];
            $retcode['package']='Sign=WXPay';
            $retcode['timestamp']=time();
            $retcode['sign']=self::MakeSign($retcode);
            $data = [
                'data' => $retcode,
                'ordernumber' => $orderNumber
            ];
            return ['status'=>'success','data'=>$data];
        }
    }

    public static function MakeSign($data) {
        $wxpayconfig = new \WxPayConfig();
        ksort($data);
        $string = self::ToUrlParams($data);
        $string = $string . "&key=".$wxpayconfig::KEY;
        $string = md5($string);
        $result = strtoupper($string);
        return $result;
    }

    public static function ToUrlParams($data) {
        $buff = "";
        foreach ($data as $k => $v) {
            if($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    static function rsaSign($data, $private_key) {
        $private_key=str_replace("-----BEGIN RSA PRIVATE KEY-----","",$private_key);
        $private_key=str_replace("-----END RSA PRIVATE KEY-----","",$private_key);
        $private_key=str_replace("\n","",$private_key);

        $private_key="-----BEGIN RSA PRIVATE KEY-----".PHP_EOL .wordwrap($private_key, 64, "\n", true). PHP_EOL."-----END RSA PRIVATE KEY-----";

        $res=openssl_get_privatekey($private_key);

        if($res)
        {
            openssl_sign($data, $sign,$res);
        }
        else {
            echo "您的私钥格式不正确!"."<br/>"."The format of your private_key is incorrect!";
            exit();
        }
        openssl_free_key($res);
        //base64编码
        $sign = base64_encode($sign);
        return $sign;
    }

    static function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key."=".$val."&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);

        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

        return $arg;
    }

    static function createLinkstringUrlencode($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key."=".urlencode($val)."&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);

        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

        return $arg;
    }
}